import { OnInit, OnChanges, OnDestroy, Component, ChangeDetectionStrategy, ViewEncapsulation, Input, TemplateRef, NgZone, ViewChild, ElementRef } from '@angular/core';
import { InputNumber, InputBoolean } from 'ng-zorro-antd';
import { Subscription } from 'rxjs';
import { SupData } from '@core/lb/SupData';

declare var G2: any;
const TITLE_HEIGHT = 41;

@Component({
  selector: 'lb-bar',
  templateUrl: './barChart.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush, // 检测改为按需，即不自动刷新
})
export class LbBarChartComponent implements OnInit, OnChanges, OnDestroy {

  private chart: any;
  private resize$: Subscription;

  @ViewChild('container', { static: true }) private node: ElementRef;


  /**
   * 延迟加载
   */
  @Input() @InputNumber() delay = 0;
  /**
   * 标题
   */
  @Input() title: string | TemplateRef<void>;
  /**
   * 颜色
   */
  @Input() color: string[] = null;
  @Input() colorFiled = 'name';
  /**
   * 报表高度
   */
  @Input() @InputNumber() height = 200;
  /**
   * padding
   */
  @Input() padding: Array<number | string> | string = 'auto';
  /**
   * 报表数据
   */
  @Input() data: any[] = [];
  /**
   * 宽度较少时，是否延迟标签
   */
  @Input() @InputBoolean() autoLabel = true;

  /**
   * 坐标字段
   */
  @Input() position: { x: string, y: string, z: string };

  alias: any = {};

  /**
   * 百分比图
   */
  @Input() @InputBoolean() percent = true;


  constructor(private ngZone: NgZone, private supdata: SupData) { }

  install(resdata) {


    // 图表信息
    let dataFilds: string[] = resdata.message.tb.DAA035.split(',');
    const groupFileds: string[] = resdata.message.tb.DAA036.split(',');

    if (resdata.message.tb.DAA045) {
      dataFilds = JSON.parse(resdata.message.tb.DAA045)
    }

    this.alias[dataFilds[0]] = { alias: resdata.message.data[dataFilds[0]].DAA022 }

    let data: any[] = this.supdata.rebuildData(resdata.message.data, resdata.message.tb, groupFileds, groupFileds);

    // 字典转化
    data = this.supdata.rebuildDsDataToLabel(data);

    this.position = { x: groupFileds[0], y: dataFilds[0], z: '' };

    if (dataFilds.length > 1 && groupFileds.length <= 1) {
      // this.position.z=dataFilds[1];

      // 需要将多个指标合成到一个
      const { DataView } = DataSet;
      const dv = new DataView().source(data);

      dv.transform({
        type: 'fold',
        fields: dataFilds,
        key: 'DAA020',
        value: '值' // value字段
      });

      data = dv.rows;
      data = this.supdata.rebuildDsDataToLabel(data);

      // data.map(d=>{
      //    d.值= (d.值/10000).toFixed(2);
      // })


      this.position = resdata.message.tb.DAA044 ? { x: 'DAA020', y: '值', z: groupFileds[0] } : { x: groupFileds[0], y: '值', z: 'DAA020' };

    }
    if (groupFileds.length > 1) {
      this.position.z = groupFileds[1];
    }


    this.data = data;
    this.render();
  }

  render() {
    const { node, padding } = this;
    const container = node.nativeElement as HTMLElement;

    const chart = (this.chart = new G2.Chart({
      container,
      forceFit: true,  // 图表的宽度自适应开关

      height: this.getHeight(),
      padding,
    }));

    chart.tooltip(true,{
      showTitle: false,
    });


    if (this.percent) {
      const label = {};
      label[this.position.y] = {
        max: 1.0,
        min: 0.0,
        nice: false,
      };
      chart.source(this.data, label);
    } else {
      chart.source(this.data);
    }


    chart.axis(this.position.y, { label: null, });

    chart.legend(false);
    chart.coord().transpose();


    if (this.position.z) {
      chart.intervalStack().position(`${this.position.x}*${this.position.y}`).color(this.position.z)
    } else {
      chart.interval().position(`${this.position.x}*${this.position.y}`).size(26)
        .opacity(1).label(this.position.y, {
          textStyle: {
            fill: '#8d8d8d'
          },
          offset: 10
        });
    }


    chart.render();

  }

  attachChart(resdata) {
    // const { chart, padding, data, color } = this;
    // if (!chart || !data || data.length <= 0) return;
    // const height = this.getHeight();
    // if (chart.get('height') !== height) {
    //   chart.changeHeight(height);
    // }
    //  // color
    //  chart.get('geoms')[0].color(this.colorFiled,this.color);
    //  chart.set('padding', padding);
    //  chart.changeData(data);

    const dataFilds: string[] = resdata.message.tb.DAA035.split(',');
    const groupFileds: string[] = resdata.message.tb.DAA036.split(',');

    this.alias[dataFilds[0]] = { alias: resdata.message.data[dataFilds[0]].DAA022 }

    let data = this.supdata.rebuildData(resdata.message.data, resdata.message.tb, groupFileds, groupFileds);
    // 字典转化
    data = this.supdata.rebuildDsDataToLabel(data);



    if (dataFilds.length > 1 && groupFileds.length <= 1) {
      // this.position.z=dataFilds[1];

      // 需要将多个指标合成到一个
      const { DataView } = DataSet;
      const dv = new DataView().source(data);

      dv.transform({
        type: 'fold',
        fields: dataFilds,
        key: 'DAA020',
        value: '值' // value字段
      });

      data = dv.rows;
      data = this.supdata.rebuildDsDataToLabel(data);

    }

    this.data = data;
    this.updateChart();

  }

  updateChart() {
    const { chart, data } = this;
    if (chart) {
      chart.changeData(data);
    }


  }

  destroy() {
    if (this.resize$) {
      this.resize$.unsubscribe();
    }
    if (this.chart) {
      this.ngZone.runOutsideAngular(() => this.chart.destroy());
    }
  }

  /**
   * 报表高度
   * 存在报表头，则需要减掉报表头的高度
   */
  getHeight() {
    return this.title ? this.height - TITLE_HEIGHT : this.height;
  }


  ngOnInit(): void {
    if (this.position && this.data.length > 0) {
      this.ngZone.runOutsideAngular(() => setTimeout(() => this.render(), this.delay));
    }

  }

  ngOnChanges(changes: import("@angular/core").SimpleChanges): void {
    this.ngZone.runOutsideAngular(() => this.updateChart());
  }
  ngOnDestroy(): void {
    this.destroy();
  }


}